package de.tto.dating.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;

import de.tto.dating.constants.EmailType;
import de.tto.dating.entities.User;
import de.tto.dating.servlet.RegisterServlet;

public class EmailService {

	private static final Logger log = Logger.getLogger(RegisterServlet.class
			.getName());

	public void sendAccountConfirmEmail(User user, ServletContext context)
			throws IOException {

		String confirmLinkParam = "user=" + user.getOid() + "&key="
				+ user.getConfirmKey();

		String body = new FileService()
				.readFile(context, EmailType.ACCOUNT_CONFIRM.getBody())
				.replace("#{param}", confirmLinkParam);
		doSendMail(user.getEmail(), EmailType.ACCOUNT_CONFIRM.getSubject(),
				body);
	}

	public void sendWelcomeEmail(User user, ServletContext context)
			throws IOException {

		String body = new FileService()
				.readFile(context, EmailType.WELCOME.getBody())
				.replace("#{email}", user.getEmail())
				.replace("#{password}", user.getPassword());
		doSendMail(user.getEmail(), EmailType.WELCOME.getSubject(), body);
	}

	private void doSendMail(String to, String subject, String msgBody) {

		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("timur.tokoev@googlemail.com",
					"sdating.de"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to,
					to));
			msg.setSubject(subject);
			msg.setText(msgBody);
			Transport.send(msg);

		} catch (AddressException e) {
			log.info(e.toString());
		} catch (MessagingException e) {
			log.info(e.toString());
		} catch (UnsupportedEncodingException e) {
			log.info(e.toString());
		}
	}

}
